//
//  EditPanelViewController.swift
//  ezyform
//
//  Created by Moennig Q on 8/9/2022.
//  Copyright © 2022 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
class EditPanelInfoViewController: BaseViewController {
    var refreshDetailClosure: (()->Void)?
    private lazy var disposeBag = DisposeBag()
    var customView = EditPanelInfoView()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initUI()
        let listDeepCopy = JobDetailModelHelper.shared.jobDetailModel.system_detail.panels.clone()
        self.customView.setData(listDeepCopy)
    }
    func initUI(){
        self.view = self.customView
        self.customView.setTitleInfo(R.string.localizable.editPanelInformation())
        //MARK: - save 事件
        self.customView.saveBtn.rx.tap.subscribe(onNext: { [weak self] _ in
            guard let strongSelf = self else { return  }
            strongSelf.customView.endEditing(true)
            strongSelf.toSavePanelInfo()
        }).disposed(by: self.disposeBag)
        //MARK: - 增加一行Panel
        self.customView.addBtn.rx.tap.subscribe { [weak self] _ in
            guard let strongSelf = self else { return  }
            strongSelf.customView.tableView.addOnePanel()
            strongSelf.customView.tableView.layoutIfNeeded()//会强制重绘并等待完成。
            //table view加载完，跳转到最后新增加的item的位置
            strongSelf.customView.tableView.scrollToRow(at: IndexPath(row: strongSelf.customView.tableView.list.count - 1, section: 0), at: UITableView.ScrollPosition.none, animated: true)
            
        }.disposed(by: self.disposeBag)
        
    }
    
    private func toSavePanelInfo(){
        let spvCheck = InstallationDetailVCHelper.shared.checkIfHaveOnlyOneBandForSPV(self.customView.tableView.list)//一个model才传递true，有后台处理是否开启spv
        if JobDetailModelHelper.shared.jobDetailModel.job_status == PVDJobStatusValue.scheduled.rawValue{//start job前才做校验
            //如果新的panels的数据，在老的里边找不到就要检查是否开启spv
            //1)原来没数据，全部是新增的；2）原来有数据，删除又新增
            let firstIndex = self.customView.tableView.list.firstIndex(where: {
                let brandID = $0.panel_brand_id
                for tempModel in JobDetailModelHelper.shared.jobDetailModel.system_detail.panels{
                    if tempModel.panel_brand_id == brandID{
                        return true
                    }
                }
                return false
            })
            //新增数据，再老的数据中找不到
            if firstIndex == nil {
                //先校验spv check ，确认是否开启spv
                InstallationDetailVCHelper.shared.validSPVCheckBeforeNextOperation(panels: self.customView.tableView.list, companyID: JobDetailModelHelper.shared.jobDetailModel.company_id) { [weak self] spvCheckFlag in
                    guard let strongSelf = self else { return  }
                    if spvCheckFlag {
                        strongSelf.showValidSPVCheckView()
                    }else{
                        strongSelf.savePanelInfo(spvCheck: spvCheck)
                    }
                }
            }else{
                self.savePanelInfo(spvCheck: spvCheck)
            }
        }else{//stard job后的处理
            self.savePanelInfo(spvCheck: spvCheck)
        }
    }
    
    //MARK: - 显示Valid SPV Check
    private func showValidSPVCheckView(){
        let view = CreateJobValidSPVCheckView()
        view.closure = { [weak self] spvCheck in
            self?.savePanelInfo(spvCheck: spvCheck)
        }
        self.view.addSubview(view)
        view.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    private func savePanelInfo(spvCheck: Bool){
        let vm = EditJobInfoService()
        vm.setBlockAfterNetwork { [weak self] (result, _) in
            guard let strongSelf = self else {return}
            ModelViewUtil.shared.hideUpdatingView()
            if let data = result as? PVDDetailModel{
                JobDetailModelHelper.shared.jobDetailModel.spv_check = data.spv_check
                JobDetailModelHelper.shared.jobDetailModel.system_detail = data.system_detail
            }
            strongSelf.refreshDetailClosure?()//panel更新后，要刷新detail中底部按钮barcode计划数量
            strongSelf.navigationController?.popViewController(animated: true)
            
        } errorBlock: {  (code, error) in
            ModelViewUtil.shared.hideLoadingView()
            Tool().showErrorInfo(code, error)
        }
        ModelViewUtil.shared.showLoadingView(R.string.localizable.updating())
        vm.updateSystemInfo(panelList: self.customView.tableView.list + self.customView.tableView.delList, spvCheck: spvCheck)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
        
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        DebugLog("\(self) didReceiveMemoryWarning")
    }
}
